package com.compty.paint.web.member;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.compty.core.struts2.BaseAction;
import com.compty.paint.domain.AuditState;
import com.compty.paint.domain.Gallery;
import com.compty.paint.domain.ImageInfo;
import com.compty.paint.domain.LogInfo;
import com.compty.paint.domain.ProvinceInfo;
import com.compty.paint.domain.UploadState;
import com.compty.paint.domain.support.LogTypeEnum;
import com.compty.paint.manager.AuditStateManager;
import com.compty.paint.manager.GalleryManager;
import com.compty.paint.manager.ImageInfoManager;
import com.compty.paint.manager.LogInfoManager;
import com.compty.paint.manager.PaintingManager;
import com.compty.paint.manager.ProvinceInfoManager;
import com.compty.paint.manager.UploadStateManager;
import com.compty.paint.util.Constants;
import com.compty.security.domain.User;

/**
 * @Todo:处理画廊Action
 * @author: zhuqh
 * @CreateTime:2011-8-15 上午09:04:28
 */
public class GalleryAction extends BaseAction<Gallery>{

	private static final long serialVersionUID = 577351595592761416L;
	
	private ProvinceInfoManager provinceInfoManager;
	private GalleryManager galleryManager;
	private AuditStateManager auditStateManager;
	private UploadStateManager uploadStateManager;
	private PaintingManager paintingManager;
	private LogInfoManager logInfoManager;
	private ImageInfoManager imageInfoManager;
	
	// ====================================================
	private Gallery gallery;
	private List<ProvinceInfo> provinceInfoList;
	private Date startDate;
	private Date endDate;
	private String operateStr; //1表示隐藏,2表示删除,3：审核通过 ,4:审核驳回,5:显示
	
	/**
	 *@Todo:新增预处理
	 *@author:zhuqh
	 *@CreateTime:2011-6-9 下午05:05:07
	 */
	public String addPrepare(){
		
		this.gallery = null;
		
		this.provinceInfoList = provinceInfoManager.getAll();
		
		return "addPrepare";
	}
	
	/**
	 *@Todo:保存画廊基本资料
	 *@author:zhuqh
	 *@CreateTime:2011-6-9 下午08:12:37
	 * @throws IOException
	 */
	public String save() throws Exception{
		
		if( gallery != null){
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			gallery.setEntryPerson(userInfo);
			gallery.setUploadTime(Calendar.getInstance().getTime());
			gallery.setModifyTime(Calendar.getInstance().getTime());
			
			if(Constants.Auto_Audit){
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Pass);
				gallery.setAuditState(auditState);
			}else{
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Init);
				gallery.setAuditState(auditState);
			}
			
			UploadState  uploadState = uploadStateManager.findUniqueBy("english_name", Constants.Upload_State_Init); //上传状态，是否锁定，隐藏等
			gallery.setUploadState(uploadState);
			
			if(gallery.getProvinceInfo() == null || gallery.getProvinceInfo().getId()== null){
				gallery.setProvinceInfo(null);
			}
			if(gallery.getCityInfo() == null || gallery.getCityInfo().getId() == null ){
				gallery.setCityInfo(null);
			}
			
			galleryManager.save(gallery);
			generateImageOfGalleryAfterSaved(gallery);//第一次生成图片
			
			LogInfo logInfo = buildLogInfo(LogTypeEnum.addGallery, "保存画廊"+gallery.getName()+"基本资料成功");
			logInfoManager.writeLog(logInfo);
		}
		
		return "saved";
	}
	
	/**
	 *@Todo:保存画廊基本资料(ajax提交)
	 *@author:zhuqh
	 *@CreateTime:2011-6-9 下午08:12:37
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public String save_additional() throws Exception{
		
		if( gallery != null){
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			gallery.setEntryPerson(userInfo);
			gallery.setUploadTime(Calendar.getInstance().getTime());
			gallery.setModifyTime(Calendar.getInstance().getTime());
			
			if(Constants.Auto_Audit){
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Pass);
				gallery.setAuditState(auditState);
			}else{
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Init);
				gallery.setAuditState(auditState);
			}
			
			UploadState  uploadState = uploadStateManager.findUniqueBy("english_name", Constants.Upload_State_Init); //上传状态，是否锁定，隐藏等
			gallery.setUploadState(uploadState);
			
			if(gallery.getProvinceInfo() == null || gallery.getProvinceInfo().getId()== null){
				gallery.setProvinceInfo(null);
			}
			if(gallery.getCityInfo() == null || gallery.getCityInfo().getId() == null ){
				gallery.setCityInfo(null);
			}
			
			Long gallery_Id = gallery.getId();
			List list = galleryManager.findPaintingsByGalleryId(gallery_Id);
			gallery.setPaintings(list);
			
			galleryManager.save(gallery);
			generateImageOfGalleryAfterSaved(gallery);//第一次生成图片
			
			request.setAttribute("ajaxData", "0000");
			
			LogInfo logInfo = buildLogInfo(LogTypeEnum.addGallery, "保存画廊"+gallery.getName()+"基本资料成功");
			logInfoManager.writeLog(logInfo);
		}
		
		return "save_additional";
	}
	
	/**
	 *@Todo:修改
	 *@author:zhuqh
	 *@CreateTime:2011-8-15 下午04:45:08
	 */
	public String modifyPrepare(){
		
		this.provinceInfoList = provinceInfoManager.getAll();
		
		if( gallery != null){
			Long id = gallery.getId();
			this.gallery = galleryManager.get(id);
		}
		
		return "modifyPrepare";
	}
	
	/**
	 * 修改画家信息
	 *@author:zhuqh
	 *@CreateTime:2011-6-9 上午10:19:01
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String modify() throws Exception {
		
		if(gallery != null){
			
			UploadState  uploadState = uploadStateManager.findUniqueBy("english_name", Constants.Upload_State_Init); //上传状态
			gallery.setUploadState(uploadState);
			
			if(Constants.Auto_Audit){
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Pass);
				gallery.setAuditState(auditState);
			}else{
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Init);
				gallery.setAuditState(auditState);
			}
			
			gallery.setModifyTime(Calendar.getInstance().getTime());
			gallery.setUploadTime(Calendar.getInstance().getTime());
			
			if(gallery.getProvinceInfo() == null || gallery.getProvinceInfo().getId()== null){
				gallery.setProvinceInfo(null);
			}
			if(gallery.getCityInfo() == null || gallery.getCityInfo().getId() == null ){
				gallery.setCityInfo(null);
			}
			
			Long gallery_Id = gallery.getId();
			List list = galleryManager.findPaintingsByGalleryId(gallery_Id);
			gallery.setPaintings(list);
			
			galleryManager.save(gallery);
			generateImageOfGalleryAfterSaved(gallery);//第一次生成图片
			
			LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyGallery, "修改画廊"+gallery.getName()+"基本资料成功");
			logInfoManager.writeLog(logInfo);
			
			request.setAttribute("ajaxData", "0000");
		}
		
		return "modified";
	}
	
	/**
	 *@Todo:修改状态
	 *@author:zhuqh
	 *@CreateTime:2011-6-9 上午10:19:17
	 */
	public String changeUploadState() throws Exception{
		
		if(gallery != null){
			Long id = gallery.getId();
			this.gallery = galleryManager.get(id);
			
			if("1".equals(operateStr)){ //隐藏
				UploadState  uploadState = uploadStateManager.findUniqueBy("english_name",Constants.Upload_State_Hidden);
				gallery.setUploadState(uploadState);
				gallery.setModifyTime(Calendar.getInstance().getTime());
				galleryManager.save(gallery);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyGallery, "修改画廊"+ gallery.getName() +"基本信息,operate：隐藏");
				logInfoManager.writeLog(logInfo);
				
			}else if("2".equals(operateStr)){//删除
				galleryManager.removeById(id);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.deleteGallery, "删除画廊"+ gallery.getName() +"基本信息");
				logInfoManager.writeLog(logInfo);
			}
			else if("3".equals(operateStr)){
				AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Pass);  //审核通过
				gallery.setAuditState(auditState);
				gallery.setModifyTime(Calendar.getInstance().getTime());
				galleryManager.save(gallery);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.audit_pass_gallery, "审核通过画廊"+ gallery.getName());
				logInfoManager.writeLog(logInfo);
			}
			else if("4".equals(operateStr)){
				AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Overrule);  //审核驳回
				gallery.setAuditState(auditState);
				gallery.setModifyTime(Calendar.getInstance().getTime());
				galleryManager.save(gallery);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.audit_overrule_gallery, "审核驳回画廊"+ gallery.getName());
				logInfoManager.writeLog(logInfo);
			}
			else if("5".equals(operateStr)){//显示
				UploadState uploadState = uploadStateManager.findUniqueBy("english_name", Constants.Upload_State_Init);
				gallery.setUploadState(uploadState);
				gallery.setModifyTime(Calendar.getInstance().getTime());
				galleryManager.save(gallery);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyGallery, "修改画廊"+ gallery.getName() +"基本信息,operate：显示");
				logInfoManager.writeLog(logInfo);
			}
		}
		
		request.setAttribute("ajaxData", "0000");
		
		return "changState";
	}
	
	/**
	 *@Todo:显示画廊列表（分页显示）
	 *@author:zhuqh
	 *@CreateTime:2011-8-16 上午08:58:05
	 * @return
	 */
	public String list(){
		
		  Criteria criteria;
		  
	        if (sort != null) {
	            boolean isAsc = dir.equalsIgnoreCase("asc");
	            criteria = galleryManager.createCriteria(sort, isAsc);
	        } else {
	            criteria = galleryManager.createCriteria();
	        }
	        
	        criteria.addOrder(Order.desc("id"));
	        
	        User userInfo = (User) session.getAttribute(Constants.Userinfo);
	        if(userInfo!= null && "0".equals(userInfo.getAdministratorFlag())){
	        	  criteria = criteria.add(Restrictions.eq("entryPerson", userInfo));
	        }
	        
	        if(startDate != null){
	        	 criteria = criteria.add(Restrictions.ge("uploadTime", startDate));
	        }
	        
	        if(endDate != null){
	        	 criteria = criteria.add(Restrictions.lt("uploadTime", endDate));
	        }

	        if ((filterTxt != null) && (filterValue != null)
	                && (!filterTxt.equals("")) && (!filterValue.equals(""))) {
	            criteria = criteria.add(Restrictions.like(filterTxt,
	                        "%" + filterValue + "%"));
	        }

	        this.page = galleryManager.pagedQuery(criteria, curPage, pageSize);
	        
	        return "list";
	}
	
	/**
	 * 显示画廊详情及画廊所有作品信息
	 *@author:zhuqh
	 *@CreateTime:2011-8-3 上午09:55:23
	 * @return
	 */
	public String showDetail(){
		
		this.provinceInfoList = provinceInfoManager.getAll();
		
		if(gallery != null){
			
			Long id = gallery.getId();
			this.gallery = galleryManager.get(id);
			
			String hql = "select p from Gallery e inner join  e.paintings as p where e.id= ?";
			this.page = paintingManager.pagedQuery(hql, curPage, 8, id);
		}
		
		return "showDetail";
	}
	
	/**
	 *@Todo:会员(画廊会员)管理自己的画廊基本信息
	 *@CreateTime:2011-8-20 下午04:57:18
	 */
	public String viewGalleryInformation(){
		
		this.provinceInfoList = provinceInfoManager.getAll();
		
		User user = (User) session.getAttribute(Constants.Userinfo);
		
		if( user != null){
			
			Long userId = user.getId();
			
			this.gallery = galleryManager.findGalleryByUserId(userId);
			if( gallery != null){
    			String hql = "select p from Gallery e inner join  e.paintings as p where e.id= ?";
    			this.page = paintingManager.pagedQuery(hql, curPage, 8, gallery.getId());
        	}
		}
		
		return "view_gallery_information";
	}
	
	private void generateImageOfGalleryAfterSaved(Gallery gallery) throws Exception{
		if( gallery.getImageInfo() != null){
			ImageInfo img = imageInfoManager.get(gallery.getImageInfo().getId());
			writeImg(img, Constants.ExhibitionFlag);
		}
	}

	public Gallery getGallery() {
		return gallery;
	}

	public void setGallery(Gallery gallery) {
		this.gallery = gallery;
	}

	public List<ProvinceInfo> getProvinceInfoList() {
		return provinceInfoList;
	}

	public void setProvinceInfoList(List<ProvinceInfo> provinceInfoList) {
		this.provinceInfoList = provinceInfoList;
	}

	public void setProvinceInfoManager(ProvinceInfoManager provinceInfoManager) {
		this.provinceInfoManager = provinceInfoManager;
	}

	public void setGalleryManager(GalleryManager galleryManager) {
		this.galleryManager = galleryManager;
	}

	public void setAuditStateManager(AuditStateManager auditStateManager) {
		this.auditStateManager = auditStateManager;
	}

	public void setUploadStateManager(UploadStateManager uploadStateManager) {
		this.uploadStateManager = uploadStateManager;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getOperateStr() {
		return operateStr;
	}

	public void setOperateStr(String operateStr) {
		this.operateStr = operateStr;
	}

	public void setPaintingManager(PaintingManager paintingManager) {
		this.paintingManager = paintingManager;
	}

	public void setLogInfoManager(LogInfoManager logInfoManager) {
		this.logInfoManager = logInfoManager;
	}
	
	public void setImageInfoManager(ImageInfoManager imageInfoManager) {
		this.imageInfoManager = imageInfoManager;
	}
	
}
